<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="searchOptions.staffId" placeholder="工号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="searchOptions.tel" placeholder="手机号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="searchOptions.nickName" placeholder="姓名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <!-- {{ searchOptions }} -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />

      <el-table-column label="工号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.staffId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户角色" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.userRole==0" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            维修师傅
          </el-tag>
          <el-tag v-else-if="row.userRole==1" color="#b1b3b8" style="color: rgb(255, 255, 255);border: none;">
            普通用户
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="用户状态" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.deleted==0" color="#95d475" style="color: rgb(255, 255, 255);border: none;">
            正常
          </el-tag>
          <el-tag v-else-if="row.deleted==1" color="#b1b3b8" style="color: rgb(255, 255, 255);border: none;">
            禁用
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="success" @click="handleInfo(row,$index)">
            数据
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 30px;" />
    <!-- <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" /> -->
    <!-- {{ total }} {{ listQuery }} -->

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <!-- {{ temp }} -->
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="工号" prop="staffId">
          <el-input v-model="temp.staffId" :disabled="true" />
        </el-form-item>

        <el-form-item v-if="dialogStatus==='create'" label="密码" prop="pwd">
          <el-input v-model="temp.pwd" />
        </el-form-item>

        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="temp.nickName" />
        </el-form-item>

        <el-form-item label="手机号" prop="tel">
          <el-input v-model="temp.tel" />
        </el-form-item>

        <!-- {{ temp }} -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="infoTitle" :visible.sync="dialogINFOFormVisible">

      <el-descriptions
        :column="4"
        title="数据详情"
        size="large"
      >

        <el-descriptions-item label="总订单数">{{ chartData.totalCount }}</el-descriptions-item>
        <el-descriptions-item label="已完成">{{ chartData.completedCount }}</el-descriptions-item>
        <el-descriptions-item label="处理中">{{ chartData.processingCount }}</el-descriptions-item>
        <el-descriptions-item label="更多数据">
          <el-button size="small" style="padding:4px 10px" @click="handleMoreInfo()">查看</el-button>
        </el-descriptions-item>

      </el-descriptions>
      <div style="margin-top: 10px;" />
      <el-descriptions
        :column="1"
        title="已完成数据"
        size="large"
      />
      <div style="margin-top: 10px;" />

      <line-chart :chart-data="lineChartData" />

      <div style="margin-top: 10px;" />
    </el-dialog>

  </div>
</template>

<script>
import { fetchEmployeee, createEmployeee, updateEmployeee, fetachEmployeeeInfo, deleteEmployeee } from '@/api/employeee'
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import LineChart from './components/LineChart'
import { validPhone, validNickName, validStaffId, validPwd } from '@/utils/validate'
import { MessageBox } from 'element-ui'

function compare(property, property2) {
  return function(a, b) {
    var value1 = a[property]
    var value2 = b[property]
    if (value1 !== value2) {
      return value1 - value2
    }
    return a[property2] - b[property2]
  }
}

export default {
  name: 'Ordermanager',
  components: { LineChart },
  directives: { waves },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    const validateNickName = (rule, value, callback) => {
      if (!validNickName(value)) {
        callback(new Error('姓名不符合规则'))
      } else {
        callback()
      }
    }
    const validateStaffId = (rule, value, callback) => {
      if (!validStaffId(value)) {
        callback(new Error('请输入正确的ID'))
      } else {
        callback()
      }
    }

    const validatePwd = (rule, value, callback) => {
      if (!validPwd(value)) {
        callback(new Error('请输入6-18位的正确密码'))
      } else {
        callback()
      }
    }

    return {
      chartData: {
        completedCount: '',
        processingCount: '',
        totalCount: ''
      },
      lineChartData: { xlabel: [], completedCount: [] },
      employeeName: ['20001 张三', '20002 李四', '20003 王五'],
      infoTitle: '详情',
      times: ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'],
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      searchOptions: {
        staffId: '',
        tel: '',
        nickName: ''
      },
      dormitoryOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      failureTypeOptions: ['网速太慢', '无法上网', '其他原因'],
      orderProcessOptions: ['待处理', '处理中', '已完成'],
      showReviewer: false,
      temp: {
        userName: '',
        staffId: '',
        tel: '',
        nickName: '',
        userRole: 0,
        deleted: 0,
        createTime: '',
        pwd: ''
      },
      dialogFormVisible: false,
      dialogINFOFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        info: '详情'
      },
      rules: {
        staffId: [{ required: true, trigger: 'change', validator: validateStaffId }],
        nickName: [{ required: true, trigger: 'change', validator: validateNickName }],
        tel: [{ required: true, trigger: 'change', validator: validatePhone }],
        pwd: [{ required: true, trigger: 'change', validator: validatePwd }]

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchEmployeee().then(response => {
        // console.log(response)
        this.ori_data = response.data.data
        // this.ori_data = orderInfo.records
        // this.ori_data.sort(compare('dormitoryId', 'bannerId'))
        // console.log(this.ori_data)
        this.list = this.ori_data.sort(compare('staffId'))
        // console.log('list', this.list)

        this.total = response.data.data.length
        // console.log(this.list)
        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleFilter() {
      const staffId = this.searchOptions.staffId
      const tel = this.searchOptions.tel
      const nickName = this.searchOptions.nickName

      let result = this.ori_data
      // console.log(result)
      if (staffId !== '') {
        result = result.filter(item => {
          // console.log(item)
          // console.log(staffId)
          if (item.tel !== undefined) {
            return (item.staffId.indexOf(staffId)) !== -1
          }
        })
      }

      if (tel !== '') {
        result = result.filter(item => {
          // console.log(item.tel, tel, typeof item.tel, typeof tel)
          if (item.tel !== undefined) {
            return (item.tel.indexOf(tel)) !== -1
          }
        })
      }

      if (nickName !== '') {
        result = result.filter(item => {
          if (item.tel !== undefined) {
            return (item.nickName.indexOf(nickName)) !== -1
          }
        })
      }
      // console.log(result)
      this.list = result
      this.total = result.length
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        userName: '',
        staffId: '',
        tel: '',
        nickName: '',
        userRole: 0,
        deleted: 0,
        createTime: '',
        pwd: ''
      }
    },

    handleCreate() {
      // console.log('hello')
      this.resetTemp()

      this.temp.staffId = Number(this.list[this.total - 1].staffId) + 1
      this.temp.userName = this.temp.staffId

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.userName = tempData.staffId

          createEmployeee(tempData).then(() => {
            tempData.createTime = new Date().toISOString()
            this.list.unshift(tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleInfo(row, index) {
      this.temp = row
      this.dialogINFOFormVisible = true
      const data = { 'staffId': row.staffId }
      fetachEmployeeeInfo(data).then(response => {
        this.chartData = response.data.data
        this.lineChartData.xlabel = response.data.data.mouthCompletedOrderCountList.monthList
        this.lineChartData.completedCount = response.data.data.mouthCompletedOrderCountList.completedCountList
      })
    },
    handleMoreInfo() {
      this.$router.push({ path: `/ordermanager/ordermanager?staffId=${this.temp.staffId}` })
    },
    handleUpdate(row) {
      // console.log(row)
      this.temp = row
      // this.temp.orderProcess = this.orderProcessOptions[row.orderProcess]
      // this.temp.employeeName = '20001 张三'

      // console.log(this.temp)
      // this.temp.orderProcess = this.orderProcessOptions[row.orderProcess]

      // this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        // console.log(valid)
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.orderProcess = this.orderProcessOptions.findIndex(tempData.orderProcess)
          // console.log(tempData)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464

          updateEmployeee(tempData).then(() => {
            const index = this.list.findIndex(v => v.staffId === tempData.staffId)
            this.list.splice(index, 1, tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
          })

          // location.reload()
        }
      })
    },
    handleDelete(row, index) {
      MessageBox.confirm('您将要禁用该员工,是否确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteEmployeee({ 'staffId': row.staffId }).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      })
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['工号', '姓名', '手机号', '用户角色', '用户状态', '创建时间']
        const filterVal = ['staffId', 'nickName', 'tel', 'userRole', 'deleted', 'createTime']
        const data = this.formatJson(filterVal)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-employees'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j.split('.')[0] === 'detail') {
            // console.log(v['detail'][j.split('.')[1]])
            return v['detail'][j.split('.')[1]]
          } else {
            // console.log(v[j])
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }}

</script>

